package com.epam.qanda.web.servlet.questionlist;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringEscapeUtils;

import com.epam.qanda.db.model.QuestionCategory;
import com.epam.qanda.db.service.QuestionCategoryService;

public class FindServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Integer COUNT = 20;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		QuestionCategoryService questionService = new QuestionCategoryService();
		List<QuestionCategory> questions = questionService.getAllQuestions();

		// String findText = new
		// String(request.getParameter("findText").getBytes("ISO-8859-1"),
		// "UTF-8");

		String findText = request.getParameter("findText");
		request.removeAttribute("findText");
		request.setAttribute("findText", findText);
		findText = changeText(findText);
		String[] findWords = findText.split("\\s+|(?=[,/;:?!\\)\"\'])|(?<=[\"\'\\(/])|([.]$)");
		List<Integer> kstWords = new ArrayList<Integer>();
		List<List<String>> notFindWords = new ArrayList<List<String>>();
		for (int j = 0; j < questions.size(); j++) {
			int i = 0;
			List<String> notF = new ArrayList<String>();
			for (String word : findWords) {
				if (((StringEscapeUtils.unescapeHtml4(questions.get(j).getTitle().toLowerCase())
						.indexOf(word.toLowerCase()) != -1) || (StringEscapeUtils
						.unescapeHtml4(questions.get(j).getText()).toLowerCase()
						.indexOf(word.toLowerCase()) != -1))
						&& (!word.equals(""))) {
					i++;
				} else {
					notF.add(word);
				}
			}
			kstWords.add(i);
			notFindWords.add(notF);
		}
		sortResult(kstWords, questions, notFindWords);
		for (int i = questions.size() - 1; i >= 0; i--) {
			if (kstWords.get(i) == 0) {
				questions.remove(i);
				notFindWords.remove(i);
			}
		}
		Integer offset = 0;

		String off = request.getParameter("offset");
		if (off != null) {
			offset = Integer.parseInt(off.trim());
			request.removeAttribute("offset");
		}
		List<QuestionCategory> newQuestions = new ArrayList<QuestionCategory>();
		for (int i = offset; i < offset + COUNT; i++) {
			if (i < 0 || i >= questions.size())
				continue;
			newQuestions.add(questions.get(i));
		}
		request.setAttribute("action", request.getRequestURI());
		request.setAttribute("questions", newQuestions);
		request.setAttribute("offset", offset);
		request.setAttribute("size", questions.size());

		request.setAttribute("notFind", notFindWords);
		request.setAttribute("findText", StringEscapeUtils.escapeHtml4(findText));
		request.getRequestDispatcher("WEB-INF/pages/questionsPage.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	private void sortResult(List<Integer> arr, List<QuestionCategory> q,
			List<List<String>> notFindWords) {
		for (int i = 1; i < arr.size(); i++) {
			int valueToSort = arr.get(i);
			QuestionCategory tmp = q.get(i);
			List<String> n = notFindWords.get(i);

			int j = i;
			while (j > 0 && arr.get(j - 1) < valueToSort) {
				arr.set(j, arr.get(j - 1));
				q.set(j, q.get(j - 1));
				notFindWords.set(j, notFindWords.get(j - 1));
				j--;
			}
			arr.set(j, valueToSort);
			q.set(j, tmp);
			notFindWords.set(j, n);
		}
	}

	private String changeText(String t) {
		String text = t;
		text = text.trim();
		return text;
	}

}
